<template>
	<!-- 选择模版组件 -->
	<view>
		<view ref="template" type="left" background-color="#fff">
			<view class="templateBox">
				<!-- 	<view class="templateImageBox">
					<view v-for="item,index in List" :key="index" @click="selectTemplate(index)">
						<image :class="current==index?'imgBorder active':'imgBorder'" :src="item.TempImg" mode="aspectFit"> </image>
					</view>
				</view> -->
				<!-- 	<uni-data-select v-model="favId" :localdata="favList" @change="favChange"
					placeholder="请选择收藏封面"></uni-data-select> -->
				<view v-if="detailList.length>0" ref="baseForm" label-width="75px" class="form"
					style="margin: 0 20rpx;border: 1px solid #ccc;">
					<view class="" v-for="item,index in detailList" :key="index">
						<view>
							<view class="" v-if="item.ControlType=='input'" style="display: flex;padding-left: 60px;">
								<uni-easyinput v-model="item['ControlValue']" style="width: 80%;margin-top: 25rpx;"
									:placeholder="item['ControlKey']==='UnitName'?'请输入建设单位':item['ControlKey']==='ReportName'?'请输入报告名称':'请输入编制人/公司名称'"
									@input="inputChange" @clear="inputClear" />
							</view>


							<view class="flexBox" v-else-if="item.ControlType=='image'"
								:class="[item.ControlKey==='CompanyLogo'?'flexStart':'flexCenter']">
								<!-- 判断公司log上传区域和项目上传区域的大小 -->
								<view v-if="item.ControlKey==='ProjectImg'" class="upload" @click="uploadImg(item)"
									style="margin-top: 50rpx;margin-bottom: 100rpx;">
									<view v-if="!item.ControlValue"
										style="display: flex;flex-direction: column;color:#CCCCCC"><uni-icons
											type="plusempty" size="40" color="#ccc"></uni-icons>项目图片</view>
									<image v-else :src="item.ControlValue" mode="aspectFit"></image>
								</view>
								<view v-if="item.ControlKey==='CompanyLogo'" class="uploadLogo"
									@click="uploadImg(item,'logo')">
									<view v-if="!item.ControlValue"
										style="display: flex;flex-direction: column;color:#CCCCCC"><uni-icons
											type="plusempty" size="40" color="#ccc"></uni-icons>LoGo</view>
									<image v-else :src="item.ControlValue" mode="aspectFit"></image>
								</view>
							</view>
							<view class="" v-else-if="item.ControlType=='Date'"
								style="display: flex;padding-left: 160px;margin-top: 20rpx;">
								<uni-datetime-picker type="date" :clear-icon="false" v-model="item['ControlValue']" />
							</view>

						</view>
					</view>
				</view>

				<uni-fab v-if="options.ProjectId" ref="fab" :pattern="pattern" :content="fabList" horizontal="right"
					vertical="bottom" direction="horizontal" @trigger="trigger" />
				<uni-popup ref="templateDialog" type="dialog">
					<uni-popup-dialog ref="inputClose" mode="input" title="模板名称" placeholder="请输入收藏模板名称"
						@confirm="dialogConfirm"></uni-popup-dialog>
				</uni-popup>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getNowDate
	} from '@/utils/tools.js'
	import templateVue from './template.vue'
	export default {
		props: ['reportName'],
		data() {
			return {
				current: null,
				favIndex: null,
				List: [],
				detailList: [],
				favId: '',
				favList: [],
				fabList: [
					// {
					// 	iconPath: '/static/star.png',
					// 	selectedIconPath: '/static/fixbtn/star2.png',
					// 	text: '收藏',
					// 	active: false
					// },
					// {
					// 	iconPath: '/static/fixbtn/PDFPreView.png',
					// 	selectedIconPath: '/static/fixbtn/PDFPreView.png',
					// 	text: '预览',
					// 	active: true
					// },
					{
						iconPath: '/static/fixbtn/clear-off.png',
						selectedIconPath: '/static/fixbtn/clear-on.png',
						text: '清空',
						active: true
					},
					{
						iconPath: '/static/fixbtn/save-off.png',
						selectedIconPath: '/static/fixbtn/save-on.png',
						text: '保存',
						active: true
					}
				],
				pattern: {
					buttonColor: '#d1100b',
					selectedColor: '#d1100b',
					icon: 'more-filled',
					iconShow: 'more'
				},
				// 传递过来的项目id
				ProjectId: "",
				uploadImageItem: {},
				options: {},
				editItemRow: {},
				ReportName: "" //报告详情页面传递过来的报告名称

			}
		},
		// 监听顶部左侧返回按钮事件
		onBackPress() {
			let pages = getCurrentPages();
			let prevPage = pages[pages.length - 2]; //上一个页面
			prevPage.$vm.$refs.templateContent.getFavList()
			console.log('获取返回数据', )

		},
		onShow() {

			// 判断缓存中是否存在上传的公司Logo图片和项目图片做对应处理
			let cameraUploadImage = uni.getStorageSync('cameraUploadImage')
			let cameraUploadImageType = uni.getStorageSync('cameraUploadImageType')
			if (cameraUploadImage && cameraUploadImageType) {
				let obj = {
					cameraUploadImage: cameraUploadImage,
					cameraUploadImageType: cameraUploadImageType
				}
				// 将渠道的缓存上传项目图片和公司log图片赋值
				this.uploadImageResult(obj)
				// 随时移除缓存
				uni.removeStorageSync('cameraUploadImageType')
				uni.removeStorageSync('cameraUploadImage')
			}
		},
		watch: {
			favId: {
				handler(n, o) {
					if (n) {
						// this.fabList[0].active = true
						// this.fabList[0].text = '取消收藏'
					} else {
						// this.fabList[0].active = false
						// this.fabList[0].text = '收藏'
					}
				}
			},
			cameraUploadImage(n, o) {
				console.log('是否监听到裁剪图片有数据', n, o)
			}
		},
		onLoad(options) {
			console.log(getNowDate());
			this.options = options
			if (this.options.item) {
				this.editItemRow = JSON.parse(this.options.item)
				this.detailList = JSON.parse(this.editItemRow.Detailed)
				console.log(this.editItemRow);
				console.log(this.detailList);
				this.detailList.forEach(item => {
					if (item.ControlKey === "ReportName") {
						item.ControlValue = options.ReportName || item.ControlValue
					}
					if (item.ControlType == 'Date') {
						item.ControlValue = getNowDate()
					}

				})
			}
			console.log('获取传递过来的template类型', this.options, this.editItemRow, this.detailList)
			if (options.type === '新增') { //只有新增的时候再调用  
				this.ProjectId = options.ProjectId
				this.ReportName = options.ReportName
				this.getDataList()
				this.getFavList(options.ProjectId)
			}

			// 判断是新建还是编辑 如果是新建 默认关闭浮动导航栏按钮
			if (this.options.type === '新增') {
				this.favId = ""
				this.fabList[0].active = false //关闭清空
				this.fabList[1].active = false //关闭完成
			}

		},
		methods: {
			// 表单
			inputClear() {
				console.log('表单清空', this.detailList)
				let value = 0
				this.detailList.forEach(item => {
					if (item.ControlValue === "") {
						value += 1
					}
				})
				console.log('获取value', value)
				if (value == 5) { //说明三个输入框全部清空了。。关闭完成和
					this.fabList[0].active = false
					this.fabList[1].active = false
				}
			},
			// 表单输入框实时输入事件
			inputChange(e) {
				console.log('实时输入', e)
				if (e) {
					this.fabList[0].active = true
					this.fabList[1].active = true
				}
			},
			init(ProjectId) {
				this.favIndex = null
				this.current = null
				this.favId = ''
				this.List = []
				this.favList = []
				this.detailList = []
				this.show = true
				this.getDataList()
				this.getFavList(ProjectId)
			},
			open(ProjectId) {
				this.ProjectId = ProjectId
				console.log('获取传递过来的项目id', this.ProjectId)
				this.init()
				this.$refs.template.open()
			},
			// 按钮
			trigger(e) {
				if (e.index == 0) { //点击清空
					// console.log('清空了', this.detailList)
					this.detailList.forEach(item => {
						item.ControlValue = "" //清空所有数据
						this.fabList[0].active = false //关闭清空亮起
						// this.fabList[1].active=false//关闭清空亮起
					})
					// this.removeFav()
					// if (!e.item.active) this.$refs.templateDialog.open()
					// else this.removeFav()
				} else
					//  if (e.index == 1) {
					// 	let data = uni.getStorageSync('previewData')
					// 	data.template = this.detailList
					// 	uni.setStorageSync('previewData', data)
					// 	uni.navigateTo({
					// 		url: '/pages/report/reportPreview'
					// 	})
					// } else if (e.index == 2) {
					// 	this.detailList.forEach(item => item.ControlValue = '')
					// } else 
					if (e.index == 1) { //点击保存
						console.log('最后点击完成传递的提交列表数据是-----', this.detailList)
						// let  resultIndex = 0
						// let titleString = ""
						// // 判断是否有都必填
						// this.detailList.forEach(item=>{
						// 	if(item.ControlValue === "" ||item.ControlValue ==undefined){
						// 		resultIndex+=1
						// 		titleString = item.ControlName
						// 	}
						// })
						// if(resultIndex>0){//说明有未填项
						// 	uni.showToast({
						// 		title:'请填写完整信息',
						// 		icon:'none'
						// 	})
						// 	return
						// }

						this.dialogConfirm()
						// 暂时不删除 后续需要根据需求打开即可
						// 输入报告名称
						// this.$refs.templateDialog.open()

						// return
						// this.$emit('templateData', [...this.detailList])
						// this.$refs.template.close()
						// // 默认关闭浮动按钮弹出菜单
						// this.$nextTick(function() {
						// 	this.$refs.fab.popMenu = true
						// 	this.$refs.fab.isShow = false
						// })
					}
			},
			// 选择收藏
			favChange(e) {
				console.log('favCahnge时间', e);
				if (!e) {
					this.favIndex = null
					this.detailListGetData()
				} else {
					// 通过收藏Id获取对应下标后赋值新模板
					this.favIndex = this.favList.findIndex(item => item.Id == e)
					// console.log('匹配到这里了', this.favList, this.favIndex, e)
					this.detailList = JSON.parse(this.favList[this.favIndex].Detailed)
					// 通过收藏下标获取赋值模板选中状态
					this.current = this.List.findIndex(item => item.Id == this.favList[this.favIndex].TempId)

					console.log('获取赋值后的detaillist', JSON.parse(this.favList[0].Detailed), this.detailList)
				}
			},
			// 保存收藏
			dialogConfirm() {
				// if (!e) return uni.showToast({暂时不删除 后续需要打开即可
				// 	icon: 'none',
				// 	title: '请输入模板名称'
				// })
				console.log('获取即将要传递加进去的数据--------------------------------', this.detailList, this.List)
				// 报告名称和报告时间非空验证
				if (this.detailList.length > 0) {
					if (this.detailList[2].ControlValue == undefined || this.detailList[2].ControlValue === "") {
						uni.showToast({
							title: '报告名称必填',
							icon: "none"
						})
						return
					}
					if (this.detailList[this.detailList.length - 1].ControlValue === "") {
						uni.showToast({
							title: '报告时间必填',
							icon: "none"
						})
						return
					}
				}
				this.$nextTick(function() {
					console.log('获取是否展开菜单了', this.$refs.fab.popMenu, this.$refs.fab.isShow)
					this.$refs.fab.popMenu = true
					this.$refs.fab.isShow = false
				})
				let editItemRow = this.editItemRow
				let paramsData = {}
				// 判断是新增还是编辑
				if (this.options.type === '新增') { //走新增逻辑

					console.log('走新增逻辑')
					paramsData = {
						"UserId": uni.getStorageSync('userInfo').Id,
						"Name": "", //暂时没有不传
						"TempId": this.List[this.current].Id,
						"Detailed": JSON.stringify(this.detailList),
						// 项目id
						ProjectId: this.ProjectId,
					}

				} else { //走编辑
					console.log('走编辑逻辑')
					editItemRow.Detailed = JSON.stringify(this.detailList)
					paramsData = this.editItemRow || editItemRow
				}
				console.log('可以继续执行了------------', paramsData)
				// if(this.fabList[1].active==false) return uni.showToast({
				// 	title:'请填写完整信息后再保存',
				// 	icon:"none"
				// })

				uni.showLoading({
					title: this.options.type === '新增' ? '添加中' : '修改中'
				})
				this.$http('Base_Template/Base_TemplateCollect/SaveTemplateCollectData', paramsData).then(res => {
					if (res.Success) {
						uni.showToast({
							title: this.options.type === '新增' ? '已添加' : '已修改'
						})
						// this.getFavList(true)
						// this.fabList[0].active = true
						// this.fabList[0].text = '取消收藏'
						setTimeout(function() {
							uni.hideLoading()
							uni.navigateBack() //返回上一页
						}, 1000)

					} else uni.showToast({
						icon: 'none',
						title: res.Msg
					})
				})
			},
			// 取消收藏
			removeFav() {
				this.$http('Base_Template/Base_TemplateCollect/CancelFavoriteData', this.favList[this.favIndex]).then(
					res => {
						if (res.Success) {
							this.favId = ''
							this.favIndex = null
							this.fabList[0].active = false
							this.fabList[0].text = '收藏'
							uni.showToast({
								icon: 'none',
								title: '操作成功'
							})
							this.getFavList()
						} else uni.showToast({
							icon: 'none',
							title: res.Msg
						})

					})
			},
			// 模板选择
			selectTemplate(index) {
				if (index == this.current) return
				this.favId = ''
				this.current = index
				this.detailListGetData()
			},
			detailListGetData() {
				this.detailList = JSON.parse(this.List[0].Detailed).sort((a, b) => a.Sort - b.Sort)
				this.detailList.forEach(item => {
					if (item.ControlType == 'Date') item.ControlValue = getNowDate()
					else if (item.ControlKey == 'ReportName') item.ControlValue = this
						.ReportName //赋值报告详情页面传递过来的报告名称赋值新增封皮模版表单的报告名称

				})

				console.log('获取detailListGetDatadetailListGetData数据', this.detailList)
			},
			getFavList(fav) {
				this.$http('Base_Template/Base_TemplateCollect/GetTemplateCollectList?ProjectId=' + this.ProjectId, {
					SortField: "CreateTime",
					SortType: "desc",
				}).then(res => {
					if (res.Success) {
						console.log('添加和编辑生成的结果11111111111111111111111111', res.Data)
						this.favList = res.Data.map(item => {
							return {
								...item,
								text: item.Name,
								value: item.Id
							}
						})
						// if (this.options.type === '编辑') {
						// 	// 通过收藏Id获取对应下标后赋值新模板
						// 	this.favIndex = this.favList.findIndex(item => item.Id == this.options.Id)
						// 	console.log('匹配到这里了', this.favList, this.favIndex, this.options.Id)
						// 	this.detailList = JSON.parse(this.favList[this.favIndex].Detailed)
						// 	// 通过收藏下标获取赋值模板选中状态
						// 	this.current = this.List.findIndex(item => item.Id == this.favList[this.favIndex].TempId)
						// }

						if (fav) {
							this.favId = this.favList[0].value
							this.favIndex = 0
						}
					} else uni.showToast({
						icon: 'none',
						title: res.Msg
					})
				})
			},
			getDataList() {
				this.$http('Base_Template/Base_PDFTemplate/GetPDFTemplateList').then(res => {
					if (res.Success) {
						this.List = res.Data
						if (this.List.length > 0) {
							this.current = 0
							this.detailListGetData()
						}
					}
				})
			},
			// 处理选中的图片裁剪赋值对应上传区域
			uploadImageResult(data) {
				console.log('获取template函数data', data)
				if (data.cameraUploadImageType === 'CompanyLogo') { //公司log上传
					this.uploadImageItem.ControlValue = data.cameraUploadImage
				}
				if (data.cameraUploadImageType === 'ProjectImg') { //项目图片上传
					this.uploadImageItem.ControlValue = data.cameraUploadImage
				}
			},
			uploadImg(item, str) {
				console.log(str);
				console.log('上传了', item, this.options)
				this.uploadImageItem = item
				let width = str ? 600 : 800
				let height = str ? 600 : 450
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					crop: {
						quality: 50,
						width: width,
						height: height
					},
					success: (result) => {
						console.log('获取template即将要裁剪的图片结果', result);
						// 保存按钮亮起
						this.fabList[0].active = true
						this.fabList[1].active = true
						uni.showLoading({
							title: '上传中',
							mask: true
						})
						uni.uploadFile({
							url: this.$url + 'Base_Manage/Upload/ProjectImgOssUploadFileByForm?Type=' +
								item.ControlKey +
								'&ProjectId=' + this.options.ProjectId,
							// url: this.$url + 'Base_Manage/Upload/VipUserImgOssUploadFileByForm',
							filePath: result.tempFilePaths[0],
							header: {
								'Authorization': uni.getStorageSync('tokenKey')
							},
							name: 'file',
						}).then(data => {

							let [err, res] = [...data]
							console.log('获取裁剪后得到的结果', JSON.parse(res.data), err)
							setTimeout(() => {
								uni.hideLoading()
							}, 1)
							if (err !== null) return uni.showToast({
								icon: 'none',
								title: '网络连接失败,请重试',
							})
							let obj = {
								cameraUploadImage: JSON.parse(res.data).Url,
								cameraUploadImageType: item.ControlKey
							}
							// 将渠道的缓存上传项目图片和公司log图片赋值
							this.uploadImageResult(obj)
							// this.save(JSON.parse(res.data).Url)
							uni.hideLoading()
						})


					},
					fail: () => {
						uni.showToast({
							title: '网络连接失败,请重新尝试',
							icon: 'none'
						})
					}
				});
			},

			close() {
				this.show = false
				this.$refs.template.close()
			}
		}
	}
</script>

<style scoped lang="scss">
	// ::v-deep.uni-forms {
	// 	.uni-forms-item {
	// 		.uni-forms-item__label {
	// 			width: 0 !important;
	// 		}
	// 	}

	// }
	// ::v-deep.uni-forms{
	// 	uni-form{

	// 		span{
	// 			uni-view{
	// 				&:first-child{
	// 					border: 2px solid blue !important;
	// 				}

	// 			}

	// 		}
	// 	}
	// }

	.flexStart {
		display: flex !important;
		justify-content: flex-start !important;
	}

	.flexCenter {
		display: flex !important;
		justify-content: center !important;
	}

	.templateBox {
		width: 100vw;
		box-sizing: border-box;
		position: relative;

		image {
			width: 100%;
			height: 100%;
		}

		.flexBox {
			display: flex;

			.color {
				margin-left: 10px;
				color: #e43d33;
			}
		}

		.templateImageBox {
			display: flex;
			align-items: center;
			box-sizing: border-box;
			padding: 0 10px;
			padding-bottom: 5px;
			// box-shadow: 0px 3px 5px #ededed;
			overflow-x: scroll;

			.imgBorder {
				padding: 5px;
				width: 60px;
				height: 60px;
				border: 1px solid #ccc;
				border-radius: 5px;
				margin-right: 10px;
			}

			.active {
				border-color: #d1100b;
			}

		}

		.form {
			padding: 10px;
			// padding-bottom: 46px;

			.upload {
				width: 320px;
				height: 180px;
			}

			.uploadLogo {
				width: 100px;
				height: 100px;
			}

			.upload,
			.uploadLogo {
				text-align: center;
				// line-height: 100px;
				border: 2px dashed #ccc;
				border-radius: 5px;
				display: flex;
				justify-content: center;
				align-items: center;

				&:active {
					border-color: #d1100b;
				}
			}
		}

		.btnGroup {
			position: fixed;
			bottom: 0;
			width: 100%;
			display: flex;
			align-items: center;

			.confirmButton {}
		}

	}
</style>